package com.example.dmy.bootoauth.config;

import cn.hutool.crypto.digest.DigestUtil;
import com.example.dmy.bootoauth.domain.OauthUser;
import com.example.dmy.bootoauth.service.OauthUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sound.midi.Soundbank;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: daimengying
 * @Date: 2019/1/5 11:11
 * @Description:
 */
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    OauthUserService oauthUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO 这个地方可以通过username从数据库获取正确的用户信息，包括密码和权限等。
        OauthUser user= this.oauthUserService.getByUsername(username);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        if(user!=null){
            String[] roles=user.getRoles().split(",");
            for (int i=0,len=roles.length;i<len;i++){
                grantedAuthorityList.add(new SimpleGrantedAuthority(roles[i]));
            }
        }
        String secret = passwordEncoder.encode(user.getPassword());
        System.out.println("重写userservice获取的secret:"+secret);
        return new User(username, secret, grantedAuthorityList);
    }
}
